<template>
    <div class="order-container">
        <div class="page-header">
            <h1 class="page-title">我的订单</h1>
            <p class="page-subtitle">查看和管理您的订单信息</p>
        </div>
        
        <!-- 订单状态筛选 -->
        <div class="order-filters">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                <el-tab-pane label="全部订单" name="all" />
                <el-tab-pane label="待付款" name="pending" />
                <el-tab-pane label="待发货" name="paid" />
                <el-tab-pane label="待收货" name="shipped" />
                <el-tab-pane label="待评价" name="review" />
                <el-tab-pane label="已完成" name="completed" />
                <el-tab-pane label="已取消" name="cancelled" />
            </el-tabs>
        </div>
        
        <!-- 订单列表 -->
        <div class="order-list">
            <div
                v-for="order in paginatedOrders"
                :key="order.id"
                class="order-card"
            >
                <div class="order-header">
                    <div class="order-info">
                        <span class="order-number">订单号：{{ order.order_number }}</span>
                        <span class="order-time">{{ formatTime(order.created_at) }}</span>
                    </div>
                    <div class="order-status">
                        <el-tag :type="getStatusType(order.status)">
                            {{ getStatusText(order.status) }}
                        </el-tag>
                    </div>
                </div>
                
                <div class="order-details">
                    <div class="detail-row">
                        <span class="label">收货地址：</span>
                        <span class="value">{{ order.address }}</span>
                    </div>
                    <div class="detail-row">
                        <span class="label">支付方式：</span>
                        <span class="value">{{ getPayMethodText(order.pay_method) }}</span>
                    </div>
                    <div class="detail-row">
                        <span class="label">商品数量：</span>
                        <span class="value">{{ order.total_count }} 件</span>
                    </div>
                </div>
                
                <div class="order-footer">
                    <div class="order-total">
                        <span class="total-text">
                            共{{ order.total_count }}件商品 合计：
                        </span>
                        <span class="total-amount">¥{{ order.total_amount.toFixed(2) }}</span>
                    </div>
                    
                    <div class="order-actions">
                        <el-button
                            v-if="order.status === 1"
                            type="primary"
                            @click="payOrder(order)"
                        >
                            立即付款
                        </el-button>
                        
                        <el-button
                            v-if="order.status === 3"
                            type="success"
                            @click="confirmReceive(order)"
                        >
                            确认收货
                        </el-button>
                        
                        <el-button
                            v-if="order.status === 4"
                            @click="reviewOrder(order)"
                        >
                            评价订单
                        </el-button>
                        

                    </div>
                </div>
            </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty v-if="paginatedOrders.length === 0" description="暂无订单">
            <el-button type="primary" @click="goToShopping">
                去购物
            </el-button>
        </el-empty>
        
        <!-- 分页 -->
        <div class="pagination" v-if="filteredOrders.length > pageSize">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="filteredOrders.length"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, changeOrder, goPay } from '@/api/shopping'

const router = useRouter()

const orders = ref([])
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 过滤后的订单列表
const filteredOrders = computed(() => {
    let filtered = orders.value
    
    // 根据状态过滤
    if (activeTab.value !== 'all') {
        const statusMap = {
            'pending': 1,
            'paid': 2,
            'shipped': 3,
            'review': 4,
            'completed': 5,
            'cancelled': 6
        }
        const targetStatus = statusMap[activeTab.value]
        if (targetStatus !== undefined) {
            filtered = filtered.filter(order => order.status === targetStatus)
        }
    }
    
    return filtered
})

// 分页后的订单列表
const paginatedOrders = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return filteredOrders.value.slice(start, end)
})

// 更新总数
const updateTotal = () => {
    total.value = filteredOrders.value.length
}

// 监听过滤条件变化，重置分页
watch(filteredOrders, () => {
    currentPage.value = 1
    updateTotal()
}, { immediate: true })

// 获取订单列表
const fetchOrders = async () => {
    loading.value = true
    try {
        const data = await getOrder()
        console.log('订单数据:', data) // 调试用
        
        // 处理订单数据
        if (data && Array.isArray(data)) {
            orders.value = data.map(order => ({
                id: order.order_id,
                order_number: order.order_id,
                status: order.status,
                total_amount: parseFloat(order.total_amount) || 0,
                created_at: order.create_time,
                updated_at: order.update_time,
                total_count: order.total_count || 0,
                pay_method: order.pay_method,
                address: order.address,
                user: order.user
            }))
        } else {
            orders.value = []
        }
        
    } catch (error) {
        console.error('获取订单失败:', error)
        ElMessage.error('获取订单失败')
        orders.value = []
    } finally {
        loading.value = false
    }
}

// 处理标签切换
const handleTabChange = (tabName) => {
    activeTab.value = tabName
    currentPage.value = 1
    // 重新获取所有订单，然后在前端过滤
    fetchOrders()
}

// 处理分页变化
const handlePageChange = (page) => {
    currentPage.value = page
    // 分页在前端处理
}

const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    // 分页在前端处理
}

// 获取状态类型
const getStatusType = (status) => {
    const statusMap = {
        1: 'warning',   // 待支付
        2: 'success',   // 待发货
        3: 'primary',   // 待收货
        4: 'info',      // 待评价
        5: 'success',   // 已完成
        6: 'danger'     // 已取消
    }
    return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        1: '待支付',
        2: '待发货',
        3: '待收货',
        4: '待评价',
        5: '已完成',
        6: '已取消'
    }
    return statusMap[status] || '未知状态'
}

// 获取支付方式文本
const getPayMethodText = (method) => {
    const methodMap = {
        1: '支付宝',
        2: '货到付款'
    }
    return methodMap[method] || '未知支付方式'
}

// 支付订单
const payOrder = async (order) => {
    try {
        const data = await goPay(order.id)
        if (data && data.pay_url) {
            // 跳转到支付页面
            window.location.href = data.pay_url
        } else {
            ElMessage.success('支付成功')
            fetchOrders()
        }
    } catch (error) {
        console.error('支付失败:', error)
        ElMessage.error('支付失败')
    }
}

// 确认收货
const confirmReceive = async (order) => {
    try {
        await ElMessageBox.confirm('确认已收到商品？', '确认收货', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'info'
        })
        
        await changeOrder(order.id)
        ElMessage.success('确认收货成功')
        fetchOrders()
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('确认收货失败:', error)
            ElMessage.error('确认收货失败')
        }
    }
}

// 评价订单
const reviewOrder = (order) => {
    ElMessage.info('评价功能开发中...')
}

// 跳转到购物页面
const goToShopping = () => {
    router.push({ name: 'Shopping' })
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return '未知时间'
    return new Date(timeString).toLocaleString('zh-CN')
}

onMounted(() => {
    fetchOrders()
})
</script>

<style lang="less" scoped>
.order-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 30px;
    text-align: center;
    
    .page-title {
        font-size: 32px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }
    
    .page-subtitle {
        color: #7f8c8d;
        font-size: 16px;
        margin: 0;
    }
}

.order-filters {
    margin-bottom: 30px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    :deep(.el-tabs__header) {
        margin: 0;
        padding: 0 20px;
    }
    
    :deep(.el-tabs__nav-wrap) {
        padding: 0;
    }
}

.order-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .order-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
        }
        
        .order-header {
            padding: 20px 24px;
            background: #f8f9fa;
            border-bottom: 1px solid #ecf0f1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            
            .order-info {
                display: flex;
                flex-direction: column;
                gap: 4px;
                
                .order-number {
                    font-weight: 600;
                    color: #2c3e50;
                    font-size: 16px;
                }
                
                .order-time {
                    color: #7f8c8d;
                    font-size: 14px;
                }
            }
        }
        
        .order-details {
            padding: 20px 24px;
            background: #f8f9fa;
            border-bottom: 1px solid #ecf0f1;
            
            .detail-row {
                display: flex;
                justify-content: space-between;
                margin-bottom: 10px;
                
                &:last-child {
                    margin-bottom: 0;
                }
                
                .label {
                    font-size: 14px;
                    color: #7f8c8d;
                    font-weight: 500;
                }
                
                .value {
                    font-size: 14px;
                    color: #2c3e50;
                    font-weight: 600;
                }
            }
        }
        
        .order-footer {
            padding: 20px 24px;
            background: #f8f9fa;
            border-top: 1px solid #ecf0f1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            
            .order-total {
                .total-text {
                    color: #7f8c8d;
                    font-size: 14px;
                }
                
                .total-amount {
                    font-size: 18px;
                    font-weight: 600;
                    color: #e74c3c;
                    margin-left: 8px;
                }
            }
            
            .order-actions {
                display: flex;
                gap: 12px;
                
                .el-button {
                    border-radius: 6px;
                }
            }
        }
    }
}

.pagination {
    margin-top: 40px;
    display: flex;
    justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .order-container {
        padding: 15px;
    }
    
    .order-card {
        .order-header {
            padding: 16px 20px;
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
        }
        
        .order-details {
            padding: 16px 20px;
            
            .detail-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
                
                .value {
                    margin-left: 0;
                }
            }
        }
        
        .order-footer {
            padding: 16px 20px;
            flex-direction: column;
            align-items: flex-start;
            gap: 16px;
            
            .order-actions {
                width: 100%;
                justify-content: flex-end;
                flex-wrap: wrap;
            }
        }
    }
}
</style> 